package com.ng.desktop.expansionsa.view.cliente;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

import org.apache.commons.lang.StringUtils;

import com.ng.desktop.expansionsa.model.Alquiler;
import com.ng.desktop.expansionsa.model.Cliente;
import com.ng.desktop.expansionsa.model.TipoCliente;
import com.ng.desktop.expansionsa.persistence.AlquilerPersistence;
import com.ng.desktop.expansionsa.persistence.ClientePersistence;
import com.ng.desktop.expansionsa.services.NGFactoryBean;
import com.ng.desktop.expansionsa.view.alquiler.AlquilerTablePanel;
import com.ng.framework.persistence.NGSearchCriteria;
import com.ng.framework.persistence.NGSearchParameter;
import com.ng.framework.persistence.NGSearchParameter.Type;
import com.ng.framework.persistence.NGSearchParameter.UnaryOperation;
import com.ng.framework.view.desktop.NGEditDialog;
import com.ng.framework.view.desktop.NGEntitySelectorField;

public class ClienteEditDialog extends NGEditDialog<Cliente, ClientePersistence> implements ItemListener {

	private static final long serialVersionUID = 8278716092836370711L;

	private AlquilerPersistence alquilerPersistence;

	private JRadioButton radioButtonEmpresa;
	private JRadioButton radioButtonParticular;
	private JLabel labelRazonSocial;
	private JLabel labelCuit;
	private JLabel labelNombre;
	private JLabel labelApellido;
	private JLabel labelDni;
	private JTextField textFieldRazonSocial;
	private JTextField textFieldNombre;
	private JTextField textFieldApellido;
	private JTextField textFieldCuit;
	private JTextField textFieldDni;
	private JTextField textFieldDireccion;
	private JTextField textFieldPrefijoTelFijo;
	private JTextField textFieldTelFijo;
	private JTextField textFieldPrefijoCelular;
	private JTextField textFieldCelular;
	private JTextField textFieldEmail;
	private AlquilerTablePanel alquilerTablePanel;
	// private JTextField textFieldFechaRegistro;

	public ClienteEditDialog(Window owner, ClientePersistence persistence, boolean listarAlquileres) {
		this(owner, persistence, null, null, listarAlquileres);
	}

	public ClienteEditDialog(Window owner, ClientePersistence persistence, Cliente instance,
			NGEntitySelectorField<Cliente, ClientePersistence> entitySelection, boolean listarAlquileres) {
		super(owner, persistence, instance, entitySelection);
		
		this.getAlquilerTablePanel().setVisible(listarAlquileres);

		this.setTitle("Gestión de Cliente");
		
		if(listarAlquileres) {
			this.setSize(new Dimension(991, 600));			
		} else {
			this.setSize(new Dimension(671, 275));
		}
	}

	@Override
	protected JPanel createDetailPanel() {
		JPanel detailPanel = new JPanel(new GridBagLayout());

		detailPanel.add(new JLabel("Tipo de Cliente:"), new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.EAST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0));
		detailPanel.add(this.getRadioButtonEmpresa(), new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.WEST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0));
		detailPanel.add(this.getRadioButtonParticular(), new GridBagConstraints(2, 0, 1, 1, 1, 0, GridBagConstraints.WEST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 0), 0, 0));

		detailPanel.add(this.getLabelRazonSocial(), new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.EAST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0));
		detailPanel.add(this.getTextFieldRazonSocial(), new GridBagConstraints(1, 1, 2, 1, 1, 0, GridBagConstraints.WEST,
				GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0));

		detailPanel.add(this.getLabelNombre(), new GridBagConstraints(0, 2, 1, 1, 0, 0, GridBagConstraints.EAST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0));
		detailPanel.add(this.getTextFieldNombre(), new GridBagConstraints(1, 2, 2, 1, 1, 0, GridBagConstraints.WEST,
				GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0));

		detailPanel.add(this.getLabelApellido(), new GridBagConstraints(0, 3, 1, 1, 0, 0, GridBagConstraints.EAST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0));
		detailPanel.add(this.getTextFieldApellido(), new GridBagConstraints(1, 3, 2, 1, 1, 0, GridBagConstraints.WEST,
				GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0));

		detailPanel.add(this.getLabelCuit(), new GridBagConstraints(0, 4, 1, 1, 0, 0, GridBagConstraints.EAST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0));
		detailPanel.add(this.getTextFieldCuit(), new GridBagConstraints(1, 4, 2, 1, 1, 0, GridBagConstraints.WEST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 0), 0, 0));

		detailPanel.add(this.getLabelDni(), new GridBagConstraints(0, 5, 1, 1, 0, 0, GridBagConstraints.EAST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0));
		detailPanel.add(this.getTextFieldDni(), new GridBagConstraints(1, 5, 2, 1, 1, 0, GridBagConstraints.WEST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 0), 0, 0));

		detailPanel.add(new JLabel("Dirección:"), new GridBagConstraints(0, 6, 1, 1, 0, 0, GridBagConstraints.EAST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0));
		detailPanel.add(this.getTextFieldDireccion(), new GridBagConstraints(1, 6, 2, 1, 1, 0, GridBagConstraints.WEST,
				GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0));

		detailPanel.add(new JLabel("Teléfono:"), new GridBagConstraints(0, 7, 1, 1, 0, 0, GridBagConstraints.EAST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0));
		detailPanel.add(this.createPanelTelefono(false), new GridBagConstraints(1, 7, 2, 1, 1, 0, GridBagConstraints.WEST,
				GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0));

		detailPanel.add(new JLabel("Celular:"), new GridBagConstraints(0, 8, 1, 1, 0, 0, GridBagConstraints.EAST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0));
		detailPanel.add(this.createPanelTelefono(true), new GridBagConstraints(1, 8, 2, 1, 1, 0, GridBagConstraints.WEST,
				GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0));

		detailPanel.add(new JLabel("Email:"), new GridBagConstraints(0, 9, 1, 1, 0, 0, GridBagConstraints.EAST,
				GridBagConstraints.NONE, new Insets(0, 0, 5, 5), 0, 0));
		detailPanel.add(this.getTextFieldEmail(), new GridBagConstraints(1, 9, 2, 1, 1, 0, GridBagConstraints.WEST,
				GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 0), 0, 0));

		detailPanel.add(this.getAlquilerTablePanel(), new GridBagConstraints(0, 10, 3, 1, 1, 1, GridBagConstraints.CENTER,
				GridBagConstraints.BOTH, new Insets(0, 0, 5, 0), 0, 0));

		ButtonGroup buttonGroup = new ButtonGroup();
		buttonGroup.add(this.getRadioButtonEmpresa());
		buttonGroup.add(this.getRadioButtonParticular());

		return detailPanel;
	}

	private JPanel createPanelTelefono(boolean celular) {
		JPanel panelTelefono = new JPanel(new GridBagLayout());

		panelTelefono.add(new JLabel("0("), new GridBagConstraints(0, 0, 1, 1, 0, 1, GridBagConstraints.WEST,
				GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
		if (celular) {
			panelTelefono.add(this.getTextFieldPrefijoCelular(), new GridBagConstraints(1, 0, 1, 1, 0, 1,
					GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
			panelTelefono.add(new JLabel(") 15"), new GridBagConstraints(2, 0, 1, 1, 0, 1, GridBagConstraints.WEST,
					GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
			panelTelefono.add(this.getTextFieldCelular(), new GridBagConstraints(3, 0, 1, 1, 1, 1, GridBagConstraints.WEST,
					GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
		} else {
			panelTelefono.add(this.getTextFieldPrefijoTelFijo(), new GridBagConstraints(1, 0, 1, 1, 0, 1,
					GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
			panelTelefono.add(new JLabel(") "), new GridBagConstraints(2, 0, 1, 1, 0, 1, GridBagConstraints.WEST,
					GridBagConstraints.NONE, new Insets(0, 0, 0, 5), 0, 0));
			panelTelefono.add(this.geTtextFieldTelFijo(), new GridBagConstraints(3, 0, 1, 1, 1, 1, GridBagConstraints.WEST,
					GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
		}

		return panelTelefono;
	}

	private JRadioButton getRadioButtonEmpresa() {
		if (radioButtonEmpresa == null) {
			radioButtonEmpresa = new JRadioButton("Empresa", true);
			radioButtonEmpresa.addItemListener(this);
		}

		return radioButtonEmpresa;
	}

	private JRadioButton getRadioButtonParticular() {
		if (radioButtonParticular == null) {
			radioButtonParticular = new JRadioButton("Particular");
			radioButtonParticular.addItemListener(this);
		}

		return radioButtonParticular;
	}

	private JLabel getLabelRazonSocial() {
		if (labelRazonSocial == null) {
			labelRazonSocial = new JLabel("Razón Social:");
		}

		return labelRazonSocial;
	}

	private JTextField getTextFieldRazonSocial() {
		if (textFieldRazonSocial == null) {
			textFieldRazonSocial = new JTextField();
		}

		return textFieldRazonSocial;
	}

	private JLabel getLabelNombre() {
		if (labelNombre == null) {
			labelNombre = new JLabel("Nombre:");
			labelNombre.setVisible(false);
		}

		return labelNombre;
	}

	private JTextField getTextFieldNombre() {
		if (textFieldNombre == null) {
			textFieldNombre = new JTextField();
			textFieldNombre.setVisible(false);
		}

		return textFieldNombre;
	}

	private JLabel getLabelApellido() {
		if (labelApellido == null) {
			labelApellido = new JLabel("Apellido:");
			labelApellido.setVisible(false);
		}

		return labelApellido;
	}

	private JTextField getTextFieldApellido() {
		if (textFieldApellido == null) {
			textFieldApellido = new JTextField();
			textFieldApellido.setVisible(false);
		}

		return textFieldApellido;
	}

	private JLabel getLabelCuit() {
		if (labelCuit == null) {
			labelCuit = new JLabel("CUIT:");
		}

		return labelCuit;
	}

	private JTextField getTextFieldCuit() {
		if (textFieldCuit == null) {
			textFieldCuit = new JTextField(11);
			textFieldCuit.setMinimumSize(textFieldCuit.getPreferredSize());
		}

		return textFieldCuit;
	}

	private JLabel getLabelDni() {
		if (labelDni == null) {
			labelDni = new JLabel("DNI:");
			labelDni.setVisible(false);
		}

		return labelDni;
	}

	private JTextField getTextFieldDni() {
		if (textFieldDni == null) {
			textFieldDni = new JTextField(8);
			textFieldDni.setMinimumSize(textFieldCuit.getPreferredSize());
			textFieldDni.setVisible(false);
		}

		return textFieldDni;
	}

	private JTextField getTextFieldDireccion() {
		if (textFieldDireccion == null) {
			textFieldDireccion = new JTextField();
		}

		return textFieldDireccion;
	}

	private JTextField getTextFieldPrefijoTelFijo() {
		if (textFieldPrefijoTelFijo == null) {
			textFieldPrefijoTelFijo = new JTextField(4);
		}

		return textFieldPrefijoTelFijo;
	}

	private JTextField geTtextFieldTelFijo() {
		if (textFieldTelFijo == null) {
			textFieldTelFijo = new JTextField(8);
		}

		return textFieldTelFijo;
	}

	private JTextField getTextFieldPrefijoCelular() {
		if (textFieldPrefijoCelular == null) {
			textFieldPrefijoCelular = new JTextField(4);
		}

		return textFieldPrefijoCelular;
	}

	private JTextField getTextFieldCelular() {
		if (textFieldCelular == null) {
			textFieldCelular = new JTextField(8);
		}

		return textFieldCelular;
	}

	private JTextField getTextFieldEmail() {
		if (textFieldEmail == null) {
			textFieldEmail = new JTextField();
		}

		return textFieldEmail;
	}

	private AlquilerTablePanel getAlquilerTablePanel() {
		if (alquilerTablePanel == null) {
			alquilerTablePanel = new AlquilerTablePanel(this.getAlquilerPersistence());
			alquilerTablePanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Alquileres"),
					BorderFactory.createEmptyBorder(5, 5, 5, 5)));
		}

		return alquilerTablePanel;
	}

	private AlquilerPersistence getAlquilerPersistence() {
		if (alquilerPersistence == null) {
			this.alquilerPersistence = (AlquilerPersistence) NGFactoryBean.getInstance().getBean("alquilerPersistence");
		}

		return alquilerPersistence;
	}

	@Override
	protected void populateDetailPanel(Cliente instance) {
		if (instance.getTipoCliente() == TipoCliente.EMPRESA) {
			this.getRadioButtonEmpresa().setSelected(true);
			this.getTextFieldRazonSocial().setText(instance.getRazonSocial());
			this.getTextFieldCuit().setText(instance.getCuit());
		} else {
			this.getRadioButtonParticular().setSelected(true);
			this.getTextFieldNombre().setText(instance.getNombre());
			this.getTextFieldApellido().setText(instance.getApellido());
			this.getTextFieldDni().setText(instance.getDni());
		}

		this.getTextFieldDireccion().setText(instance.getDireccion());
		this.getTextFieldPrefijoTelFijo().setText(instance.getPrefijoTelefonoFijo());
		this.geTtextFieldTelFijo().setText(instance.getTelefonoFijo());
		this.getTextFieldPrefijoCelular().setText(instance.getPrefijoTelefonoCelular());
		this.getTextFieldCelular().setText(instance.getTelefonoCelular());
		this.getTextFieldEmail().setText(instance.getEmail());

		NGSearchCriteria ngSearchCriteria = new NGSearchCriteria();
		ngSearchCriteria.addNGSearchParameter(new NGSearchParameter(Alquiler.class, "cliente", String.valueOf(instance.getId()),
				Type.INTEGER, UnaryOperation.EQUALS, true, "id"));
		this.getAlquilerTablePanel().setData(this.getAlquilerPersistence().getAll(ngSearchCriteria));
	}

	@Override
	protected boolean validateInput() {
		boolean valid = true;

		boolean empresa = this.getRadioButtonEmpresa().isSelected();

		if (empresa && StringUtils.isBlank(this.getTextFieldRazonSocial().getText())) {
			JOptionPane.showMessageDialog(this, "El campo 'Razón Social' es obligatorio.", "Error", JOptionPane.ERROR_MESSAGE);
			this.getTextFieldRazonSocial().requestFocus();

			valid = false;
		} else if (empresa && StringUtils.isBlank(this.getTextFieldCuit().getText())) {
			JOptionPane.showMessageDialog(this, "El campo 'CUIT' es obligatorio.", "Error", JOptionPane.ERROR_MESSAGE);
			this.getTextFieldCuit().requestFocus();

			valid = false;
		} else if (empresa && !StringUtils.isNumeric(this.getTextFieldCuit().getText())) {
			JOptionPane.showMessageDialog(this, "El campo 'CUIT' debe ser numérico.", "Error", JOptionPane.ERROR_MESSAGE);
			this.getTextFieldCuit().requestFocus();

			valid = false;
		} else if (!empresa && StringUtils.isBlank(this.getTextFieldNombre().getText())) {
			JOptionPane.showMessageDialog(this, "El campo 'Nombre' es obligatorio.", "Error", JOptionPane.ERROR_MESSAGE);
			this.getTextFieldNombre().requestFocus();

			valid = false;
		} else if (!empresa && StringUtils.isBlank(this.getTextFieldApellido().getText())) {
			JOptionPane.showMessageDialog(this, "El campo 'Apellido' es obligatorio.", "Error", JOptionPane.ERROR_MESSAGE);
			this.getTextFieldApellido().requestFocus();

			valid = false;
		} else if (!empresa && StringUtils.isBlank(this.getTextFieldDni().getText())) {
			JOptionPane.showMessageDialog(this, "El campo 'DNI' es obligatorio.", "Error", JOptionPane.ERROR_MESSAGE);
			this.getTextFieldDni().requestFocus();

			valid = false;
		} else if (empresa && !StringUtils.isNumeric(this.getTextFieldDni().getText())) {
			JOptionPane.showMessageDialog(this, "El campo 'DNI' debe ser numérico.", "Error", JOptionPane.ERROR_MESSAGE);
			this.getTextFieldDni().requestFocus();

			valid = false;
		} else if (StringUtils.isBlank(this.getTextFieldDireccion().getText())) {
			JOptionPane.showMessageDialog(this, "El campo 'Dirección' es obligatorio.", "Error", JOptionPane.ERROR_MESSAGE);
			this.getTextFieldDireccion().requestFocus();

			valid = false;
		} else if (!this.validarTelefono(this.getTextFieldPrefijoTelFijo().getText(), this.geTtextFieldTelFijo().getText())) {
			if (StringUtils.isBlank(this.getTextFieldPrefijoTelFijo().getText())) {
				JOptionPane.showMessageDialog(this, "El código de área del campo 'Teléfono' es obligatorio.", "Error",
						JOptionPane.ERROR_MESSAGE);
				this.getTextFieldPrefijoTelFijo().requestFocus();
			} else {
				JOptionPane.showMessageDialog(this, "El número telefónico del campo 'Teléfono' es obligatorio.", "Error",
						JOptionPane.ERROR_MESSAGE);
				this.geTtextFieldTelFijo().requestFocus();
			}

			valid = false;
		} else if (!this.validarTelefono(this.getTextFieldPrefijoCelular().getText(), this.getTextFieldCelular().getText())) {
			if (StringUtils.isBlank(this.getTextFieldPrefijoCelular().getText())) {
				JOptionPane.showMessageDialog(this, "El código de área del campo 'Celular' es obligatorio.", "Error",
						JOptionPane.ERROR_MESSAGE);
				this.getTextFieldPrefijoCelular().requestFocus();
			} else {
				JOptionPane.showMessageDialog(this, "El número telefónico del campo 'Celular' es obligatorio.", "Error",
						JOptionPane.ERROR_MESSAGE);
				this.getTextFieldCelular().requestFocus();
			}

			valid = false;
		}

		return valid;
	}

	private boolean validarTelefono(String prefijo, String nroTelefono) {
		return (StringUtils.isBlank(prefijo) && StringUtils.isBlank(nroTelefono))
				|| (StringUtils.isNotBlank(prefijo) && StringUtils.isNotBlank(nroTelefono));
	}

	@Override
	protected Cliente createNewInstance() {
		return new Cliente();
	}

	@Override
	protected void populateInstance(Cliente instance) {
		if (instance.getId() == null) {
			instance.setFechaRegistro(new Date());
		}

		if (this.getRadioButtonEmpresa().isSelected()) {
			instance.setTipoCliente(TipoCliente.EMPRESA);
			instance.setRazonSocial(this.getTextFieldRazonSocial().getText());
			instance.setCuit(this.getTextFieldCuit().getText());

			instance.setNombre(null);
			instance.setApellido(null);
			instance.setDni(null);
		} else {
			instance.setTipoCliente(TipoCliente.PARTICULAR);
			instance.setNombre(this.getTextFieldNombre().getText());
			instance.setApellido(this.getTextFieldApellido().getText());
			instance.setDni(this.getTextFieldDni().getText());

			instance.setRazonSocial(null);
			instance.setCuit(null);
		}
		instance.setDireccion(this.getTextFieldDireccion().getText());
		instance.setPrefijoTelefonoFijo(this.getTextFieldPrefijoTelFijo().getText());
		instance.setTelefonoFijo(this.geTtextFieldTelFijo().getText());
		instance.setPrefijoTelefonoCelular(this.getTextFieldPrefijoCelular().getText());
		instance.setTelefonoCelular(this.getTextFieldCelular().getText());
		instance.setEmail(this.getTextFieldEmail().getText());
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		super.actionPerformed(e);

		if (e.getSource() == this.getRadioButtonEmpresa() || e.getSource() == this.getRadioButtonParticular()) {
			boolean empresa = this.getRadioButtonEmpresa().isSelected();

			this.getLabelRazonSocial().setVisible(empresa);
			this.getTextFieldRazonSocial().setVisible(empresa);
			this.getLabelCuit().setVisible(empresa);
			this.getTextFieldCuit().setVisible(empresa);

			this.getLabelNombre().setVisible(!empresa);
			this.getTextFieldNombre().setVisible(!empresa);
			this.getLabelApellido().setVisible(!empresa);
			this.getTextFieldApellido().setVisible(!empresa);
			this.getLabelDni().setVisible(!empresa);
			this.getTextFieldDni().setVisible(!empresa);
		}
	}

	@Override
	public void itemStateChanged(ItemEvent e) {
		if (e.getStateChange() == ItemEvent.SELECTED
				&& (e.getSource() == this.getRadioButtonEmpresa() || e.getSource() == this.getRadioButtonParticular())) {
			boolean empresa = this.getRadioButtonEmpresa().isSelected();

			this.getLabelRazonSocial().setVisible(empresa);
			this.getTextFieldRazonSocial().setVisible(empresa);
			this.getLabelCuit().setVisible(empresa);
			this.getTextFieldCuit().setVisible(empresa);

			this.getLabelNombre().setVisible(!empresa);
			this.getTextFieldNombre().setVisible(!empresa);
			this.getLabelApellido().setVisible(!empresa);
			this.getTextFieldApellido().setVisible(!empresa);
			this.getLabelDni().setVisible(!empresa);
			this.getTextFieldDni().setVisible(!empresa);
		}
	}

}
